package com.ruoyi.front;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysMember;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.CovertUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.front.oss.CloudVo;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.param.ParamDoc;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

@Controller
public class doc extends footcontroller {
    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private ISysTypeService iSysTypeService;
    @Autowired
    private ISysFilterService iSysFilterService;
    @Autowired
    private ISysDocService iSysDocService;
    @Autowired
    private ISysTradesetService iSysTradesetService;
    @Autowired
    private ISysGlodpotService iSysGlodpotService;
    @Autowired
    private ISysDocsetService iSysDocsetService;
    @Autowired
    private  ISysDownlogService iSysDownlogService;
    @Autowired
    private  ISysMemberService iSysMemberService;
    @Autowired
    private ISysGroupService iSysGroupService;
    @Autowired
    private  ISysFavoriteService iSysFavoriteService;
    @Autowired
    private  ISysReportItemService iSysReportItemService;
    @Autowired
    private ISysReportService iSysReportService;
    @Autowired
    private ISysCommentService iSysCommentService;
    @Autowired
    private ISysCommentAgreeService iSysCommentAgreeService;
    @Autowired
    private ISysVgroupService iSysVgroupService;
    @Autowired
    private ISysWaterService iSysWaterService;
    @Autowired
    ISysLoginsetService iSysLoginsetService;
    @Autowired
    ISysWeixinsetService iSysWeixinsetService; //支付配置
    @Autowired
    private ISysAdvService sysAdvService;
    @Autowired
    private ISysOsssetService sysOsssetService;
    private HashMap<Long,String> parentIds = new HashMap<Long, String>();
    @GetMapping({"/uploaddoc"})
    public String uploaddoc(ModelMap modelMap)
    {
        List<SysType> typeList = iSysTypeService.selectSysTypeList(new SysType());
        HashMap<Long, SysType> map=new HashMap<Long, SysType>();
        HashMap<Long, List<SysType>> hasharrlist = new HashMap<Long,List<SysType>>();
        List<SysType> tem = new ArrayList<SysType>();
        for (int i = 0; i < typeList.size(); i++) {
            map.put(typeList.get(i).getTypeid(),typeList.get(i));
        }
        for (Map.Entry<Long,SysType> entry : map.entrySet()) {

            if(hasharrlist.containsKey(entry.getValue().getPtypeid())) {
                hasharrlist.get(entry.getValue().getPtypeid()).add(entry.getValue());
            }
            else {
                tem.clear();
                tem.add(entry.getValue());
                List<SysType> list = new ArrayList<SysType>(tem);
                hasharrlist.put(entry.getValue().getPtypeid(),list);

            }


        }
        /*String str =  JSONObject.toJSONString(typeList.get(0));
        System.out.println(str);
        hasharrlist.put(0l,typeList);
        System.out.println(JSONObject.toJSONString(hasharrlist));*/
        getabout(modelMap);
        modelMap.put("json", JSONObject.toJSONString(hasharrlist));
        return "doc/upload";
    }
    @GetMapping({"/get_filter/upload/{filter}"})
    @ResponseBody
    public String getfilter(@PathVariable("filter") Integer filter) {
        List<SysType> typeList = iSysTypeService.selectSysTypeList(new SysType());
        HashMap<Long, SysType> map=new HashMap<Long, SysType>();
        HashMap<Long, List<SysFilter>> hasharrlist = new HashMap<Long,List<SysFilter>>();
        List<SysFilter> tem = new ArrayList<SysFilter>();
        for (int i = 0; i < typeList.size(); i++) {
            map.put(typeList.get(i).getTypeid(),typeList.get(i));
        }
        String strFilter = map.get((long)filter).getFilter();
        String[] itemsArray = strFilter.split(",");
        List<String> itemsList = Arrays.asList(itemsArray);
        List<SysFilter> sysFilters = iSysFilterService.selectByIds(itemsList);
        for (int i = 0; i < sysFilters.size(); i++) {
            if(hasharrlist.containsKey(sysFilters.get(i).getPid())) {
                hasharrlist.get(sysFilters.get(i).getPid()).add(sysFilters.get(i));
            }
            else {
                tem.clear();
                tem.add(sysFilters.get(i));
                List<SysFilter> list = new ArrayList<SysFilter>(tem);
                hasharrlist.put(sysFilters.get(i).getPid(),list);

            }
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hasharrlist.get(0l).size(); i++) {
            //filter_str += '<div class="doc-filter"><label>' + i +hasharrlist.get(0).get(i).getName()+ '</label><div class="ui-dropdown"><div>请选择...</div><ul>';
            sb.append("<div class=\"doc-filter\"><label>");
            sb.append(hasharrlist.get(0l).get(i).getName());
            sb.append("</label><div class=\"ui-dropdown\"><div>请选择...</div><ul>");
            for (int j = 0; j < hasharrlist.get(hasharrlist.get(0l).get(i).getId()).size(); j++) {
                sb.append("<li data-val=\"");
                sb.append(hasharrlist.get(hasharrlist.get(0l).get(i).getId()).get(j).getId());
                sb.append("\">");
                sb.append(hasharrlist.get(hasharrlist.get(0l).get(i).getId()).get(j).getName());
            }
            sb.append("</ul><input name=\"filter[]\" type=\"hidden\" value=\"0\"><i></i></div></div>");
        }

        return sb.toString();

    }
    @GetMapping({"/header_cache"})
    public String headcache(ModelMap model) {
        SysMember sysMember = ShiroUtils.getSysMember();
        if(sysMember!=null)
            model.put("sysmember",sysMember);

        model.put("userid",ShiroUtils.getSubject().getPrincipal());
        model.put("sysmember",sysMember);
        return "headercache";
    }

    //预览文档
    @GetMapping({"/detail.htm"})
    public String docdetail(HttpServletRequest request,ModelMap model,@RequestParam("docid") long docid,@RequestParam(value = "page",defaultValue ="0") int pcurrent) {
        //更新阅读次数
        iSysDocService.increaseReadcount(docid);
        SysDoc  sysDoc = iSysDocService.selectSysDocByDocid(docid);
        //获取.view 数目
        int hcount = CovertUtil.countFilesWithExtension(new File(StringUtils.getdir(sysDoc.getPath())),".view");
        //获取oss 存储的文件数目
        SysOssset sysOssset;
        sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
        if(sysOssset.getState()>0)
        {
            String docpath = iSysDocService.selectSysDocByDocid(docid).getPath();
            String pre = Constants.RESOURCE_PREFIX;
            String dirname = RuoYiConfig.getProfile();
            String path = docpath.replace(pre,"");
            String aliyun_src = path.substring(0,path.indexOf(".")) + "/";
            aliyun_src = aliyun_src.substring(1);
            OSS ossClient = new OSSClientBuilder().build(sysOssset.getEndpoint(), sysOssset.getKeyid(), sysOssset.getKeysecret());
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(sysOssset.getBucket()).withMaxKeys(1000).withPrefix(aliyun_src));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            int fileCount = sums.size()-1;
            hcount = fileCount + hcount;
            ossClient.shutdown();
        }

        //结束

        //获取交易相关参数
        List<SysTradeset> sysTradesets = iSysTradesetService.selectSysTradesetList(new SysTradeset());
        List<SysDocset> sysDocsetList = iSysDocsetService.selectSysDocsetList(new SysDocset());
        BigDecimal readpay2 = sysDoc.getReadpay();
        BigDecimal downpay2 =sysDoc.getDownpay();
        //用户相关信息(文档用户，而不是登录用户
        SysMember sysMember = iSysMemberService.selectSysMemberByUserid(sysDoc.getUserid());
        //SysMember sysMember = ShiroUtils.getSysMember();
        if(sysMember == null)
            sysMember = new SysMember();
        /*********************/
        long userid = -1;
        SysMember user = new SysMember();
        if (ShiroUtils.getSubject().getPrincipal() == null) {
            if (!(StringUtils.getCookie(request, "userid")).isEmpty()) {
                userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
            }
            user.setUserid(userid);
            user.setGroupid(0l);
            user.setVgroupid(0l);
            user.setGlods(0f);
        } else {
            user = iSysMemberService.selectSysMemberByUserid(ShiroUtils.getSysMember().getUserid());
            userid = user.getUserid();
        }
        /************************/
        SysVgroup vgroup = iSysVgroupService.selectSysVgroupByVgroupid(user.getVgroupid());
        SysGroup ugroup = iSysGroupService.selectSysGroupByGroupid(user.getGroupid());
        if(user.getUserid()!=sysDoc.getUserid()) {
            //vip折扣
            if(vgroup != null && user.getVipdate() != null && (DateUtil.compare(user.getVipdate(), DateUtil.date()) > 0 || DateUtil.compare(user.getVipdate(), DateUtil.date()) == 0)&& (vgroup.getDocmoney() == -1 || vgroup.getDocmoney() >= sysDoc.getDownpay().longValue()))
            {
                readpay2 =  sysDoc.getReadpay().multiply (sysDoc.getIsvip()>0? BigDecimal.ZERO : BigDecimal.valueOf(vgroup.getDiscount())).setScale(2,BigDecimal.ROUND_HALF_UP);
                downpay2 = sysDoc.getDownpay().multiply (sysDoc.getIsvip()>0? BigDecimal.ZERO : BigDecimal.valueOf(vgroup.getDiscount2())).setScale(2,BigDecimal.ROUND_HALF_UP);
            }
            Long paydue = sysTradesets.get(0).getPaydue();
            List<Long> typeids = Arrays.asList(-30L, -31L, -32L);
            SysGlodpot sysGlodpotread = iSysGlodpotService.findTypeUseridLinkedDue(typeids, userid, docid,paydue);
            if (sysGlodpotread != null) {
                sysDoc.setPreview((long) hcount);
                readpay2 = BigDecimal.ZERO;
            }
            typeids = Arrays.asList(-40L, -41L, -42L);
            SysGlodpot sysGlodpotdown = iSysGlodpotService.findTypeUseridLinkedDue(typeids, userid, docid,paydue);
            if (sysGlodpotdown != null) {
                sysDoc.setPreview((long) hcount);
                readpay2 = BigDecimal.ZERO;
                downpay2 = BigDecimal.ZERO;
            }
        }
        else
        {
            sysDoc.setPreview((long) hcount);
            readpay2 = BigDecimal.ZERO;
            downpay2 = BigDecimal.ZERO;
        }
        if(sysDoc.getReadpay().compareTo(BigDecimal.ZERO)==0)
            sysDoc.setPreview((long)hcount);

        //面包屑**********分类**/
        List<SysType> sysTypeList = iSysTypeService.selectSysTypeList(new SysType());
        findParentIdsById(sysDoc.getTypeid(),sysTypeList);
        List<Map.Entry<Long,String>> listids=new ArrayList<>(parentIds.entrySet());
        // 对哈希表的值进行排序
        // 对list进行排序，并通过Comparator传入自定义的排序规则
        Collections.sort(listids, new Comparator<Map.Entry<Long, String>>() {
            @Override
            public int compare(Map.Entry<Long, String> o1, Map.Entry<Long, String> o2) {
                return o1.getKey().intValue()-o2.getKey().intValue();
            }
        });
        String typeNames = "";
        String cremb = ">";
        Iterator<Map.Entry<Long,String>> iterator=listids.iterator();
        while(iterator.hasNext()){
            Map.Entry<Long,String> ite= iterator.next();
            //ids = ids + String.valueOf(ite.getKey())+"-";
            if(ite==null)
                typeNames = typeNames+"<a href='/doc.html?first="+ite.getKey()+"'>"+ite.getValue()+"</a>";
            else
                typeNames = typeNames+"<a href='/doc.html?first="+ite.getKey()+"'>"+ite.getValue()+"</a> >";
        }

        //*****************/
        //新增文档所有者信息
        model.put("member",iSysMemberService.selectSysMemberByUserid(sysDoc.getUserid()));
        //***********/
        //收藏
        SysFavorite sysFavorite = new SysFavorite();
        sysFavorite.setUserid(userid);
        sysFavorite.setDocid(sysDoc.getDocid());
        model.put("fav_state",iSysFavoriteService.selectSysFavoriteList(sysFavorite).size()>0?true:false);
        //****************/
        //举报//
        String report = "{title:'举报',body:'/doc/report.html?docid="+sysDoc.getDocid()+"',back:['举报成功', '举报失败']}";
        //****/
        //作者文档数量
        SysDoc sysDocnum = new SysDoc();
        sysDocnum.setUserid(sysDoc.getUserid());
        model.put("docnum",iSysDocService.selectSysDocList(sysDocnum).size());
        /*********/
        //文档评论
        SysComment sysComment = new SysComment();
        sysComment.setDocid(sysDoc.getDocid());
        List<SysComment> sysCommentList = iSysCommentService.selectSysCommentList1(sysComment);
        for (int i = 0 ;i<sysCommentList.size();i++)
        {
            SysCommentAgree sysCommentAgree = new SysCommentAgree();
            sysCommentAgree.setCommentid(sysCommentList.get(i).getCommentid());
            sysCommentAgree.setUserid(userid);
            if(iSysCommentAgreeService.selectSysCommentAgreeList(sysCommentAgree).size()>0)
                sysCommentList.get(i).setState(2);
            sysCommentList.get(i).setIsdel((userid==sysCommentList.get(i).getUserid())?true:false);

        }
        if(downpay2.compareTo(BigDecimal.ZERO)==0)
            model.put("downpay2",0);
        else
            model.put("downpay2",downpay2);
        if(readpay2.compareTo(BigDecimal.ZERO)==0)
            model.put("readpay2",0);
        else
            model.put("readpay2",readpay2);
        model.put("comments",sysCommentList);
        /*****************/
        model.put("report",report);
        model.put("userid",userid);
        model.put("type",typeNames);
        model.put("user",sysMember);
        //model.put("downpay2",downpay2.longValue());
        //model.put("readpay2",readpay2.longValue());
        model.put("systradesets",sysTradesets.get(0));
        model.put("sysdocset",sysDocsetList.get(0));
        model.put("sysdoc",sysDoc);
        model.put("pcurrent",pcurrent);
        model.put("hcount",hcount);
        getabout(model);
        //广告管理
        SysAdv sysAdv = new SysAdv();
        sysAdv.setState(1);
        List<SysAdv> sysAdvList = sysAdvService.selectSysAdvList(sysAdv);
        model.put("sysAdvList",sysAdvList);
        //****************/
        return "doc/docdetail";
    }
    //文档收藏
    @GetMapping({"/doc/favorite/{docid}"})
    @ResponseBody
    public Integer favorite(@PathVariable("docid") Long docid )
    {
        if(ShiroUtils.getSubject().getPrincipal() == null)
            return  -1;

        SysFavorite sysFavorite = new SysFavorite();
        sysFavorite.setUserid(ShiroUtils.getSysMember().getUserid());
        sysFavorite.setDocid(docid);
        List<SysFavorite> sysFavoriteList = iSysFavoriteService.selectSysFavoriteList(sysFavorite);
        if(sysFavoriteList.size()>0)
            iSysFavoriteService.deleteSysFavoriteByFavid(sysFavoriteList.get(0).getFavid());
        else
            iSysFavoriteService.insertSysFavorite(sysFavorite);

        return  1;
    }
    //评论提交
    @PostMapping({"/doc/comment_submit"})
    @ResponseBody
    public Integer topiccomment(SysComment sysComment)  {
        SysMember sysMember = iSysMemberService.selectSysMemberByUserid(ShiroUtils.getSysMember().getUserid());
        SysGroup sysGroup = iSysGroupService.selectSysGroupByGroupid(sysMember.getGroupid());
        if(StringUtils.contains(sysGroup.getRights(),"16"))
        {
            sysComment.setUserid(ShiroUtils.getSysMember().getUserid());
            sysComment.setState(1);
            sysComment.setDocid(sysComment.getDocid());
            sysComment.setComment(sysComment.getComment());
            iSysCommentService.insertSysComment(sysComment);
            return sysComment.getState();
        }
        else
        {
            return -1;
        }
    }
    //评论删除
    @PostMapping({"/doc/comment_del"})
    @ResponseBody
    public Integer comment_del(SysComment sysComment)  {
        SysMember sysMember = iSysMemberService.selectSysMemberByUserid(ShiroUtils.getSysMember().getUserid());
        SysGroup sysGroup = iSysGroupService.selectSysGroupByGroupid(sysMember.getGroupid());
        if(StringUtils.contains(sysGroup.getRights(),"19"))
        {

            return iSysCommentService.deleteSysCommentByCommentid(sysComment.getCommentid());
        }
        else
        {
            return -1;
        }
    }
    //文档分类
    @GetMapping({"/doc.html","/vip.html"})
    public String doc(ModelMap modelMap,@RequestParam(value = "first",defaultValue = "0") long first,@RequestParam(value = "second",defaultValue = "0") String second,@RequestParam(value = "third",defaultValue = "1") Integer third)  {
        List<SysType> typeList = iSysTypeService.selectSysTypeList(new SysType());
        HashMap<Long, SysType> map=new HashMap<Long, SysType>();
        HashMap<Long, List<SysType>> hasharrlist = new HashMap<Long,List<SysType>>();
        List<SysType> tem = new ArrayList<SysType>();
        SysType parent_array = new SysType();
        parent_array.setTypename("全部分类");
        parent_array.setFilter(String.valueOf(-1));
        parent_array.setTypeid(0l);
        for (int i = 0; i < typeList.size(); i++) {
            map.put(typeList.get(i).getTypeid(),typeList.get(i));
        }
        for (Map.Entry<Long,SysType> entry : map.entrySet()) {

            if (hasharrlist.containsKey(entry.getValue().getPtypeid())) {
                hasharrlist.get(entry.getValue().getPtypeid()).add(entry.getValue());
            } else {
                tem.clear();
                tem.add(entry.getValue());
                List<SysType> list = new ArrayList<SysType>(tem);
                hasharrlist.put(entry.getValue().getPtypeid(), list);
            }
        }
        if(first!=0) {
            typeList = hasharrlist.get(first);
            parent_array = map.get(first);
        }
        else {

            typeList = hasharrlist.get(0l);

        }
        //filter
        HashMap<Long, List<SysFilter>> filterhlist = new HashMap<Long,List<SysFilter>>();
        List<SysFilter> filtertem = new ArrayList<SysFilter>();
        String[] itemsArray = parent_array.getFilter().split(",");
        List<String> itemsList = Arrays.asList(itemsArray);
        List<SysFilter> sysFilters = iSysFilterService.selectByIds(itemsList);
        String[] fi_arr = second.split("\\.");
        String[] fi_str;
        for (int i = 0; i < sysFilters.size(); i++) {
            if(filterhlist.containsKey(sysFilters.get(i).getPid())) {
                filterhlist.get(sysFilters.get(i).getPid()).add(sysFilters.get(i));
            }
            else {
                filtertem.clear();
                filtertem.add(sysFilters.get(i));
                List<SysFilter> list = new ArrayList<SysFilter>(filtertem);
                filterhlist.put(sysFilters.get(i).getPid(),list);
            }
        }
        if(second.equals("0"))
            second = "0-0-0";
        String[] filterarr = second.split("-");
        //拼接字符串用点连接
        String filterdotstr = String.join(".",filterarr);
        System.out.println(filterarr.length);
        Long one = Long.parseLong(filterarr[0])>0?Long.parseLong(filterarr[0]):0l;
        Long two = Long.parseLong(filterarr[1])>0?Long.parseLong(filterarr[1]):0l;
        Long three = Long.parseLong(filterarr[2])>0?Long.parseLong(filterarr[2]):0l;

        //面包屑**********分类**/
        List<SysType> sysTypeList = iSysTypeService.selectSysTypeList(new SysType());
        findParentIdsById(first,sysTypeList);
        List<Map.Entry<Long,String>> listids=new ArrayList<>(parentIds.entrySet());
        Collections.sort(listids, new Comparator<Map.Entry<Long, String>>() {
            @Override
            public int compare(Map.Entry<Long, String> o1, Map.Entry<Long, String> o2) {
                return o1.getKey().intValue()-o2.getKey().intValue();
            }
        });
        String typeNames = "";
        Iterator<Map.Entry<Long,String>> iterator=listids.iterator();
        while(iterator.hasNext()){
            Map.Entry<Long,String> ite= iterator.next();
            //ids = ids + String.valueOf(ite.getKey())+"-";
            if(ite==null)
                typeNames = typeNames+"<a href='"+ite.getKey()+".html'>"+ite.getValue()+"</a>";
            else
                typeNames = typeNames+"<a href='"+ite.getKey()+".html'>"+ite.getValue()+"</a> >";
        }
        /*****************************/
        //查询文档
        //查询所有子类
        List<Long> listtype= new ArrayList<>();
        if(first!=0) {
            listtype = getAllChildIds(sysTypeList, first);
            listtype.add(first);
        }
        filterdotstr = filterdotstr.replaceAll("\\.0|0\\.", "");
        //vip和推荐
        Integer isvip = 0;
        Integer isimp = 0;
        if(third==4)
            isvip = 1;
        if(third==5)
            isimp = 1;
        List<SysDoc> sysDocList = iSysDocService.searchSysDocListBysort(listtype,filterdotstr,third,isvip,isimp);
        startPage();
        SysOssset sysOssset;
        sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
        for (int i = 0;i<sysDocList.size();i++)
        {
            if(StringUtils.localFile(sysDocList.get(i).getPath())) {
                sysDocList.get(i).setPath(serverConfig.getUrl() + StringUtils.localpng(sysDocList.get(i).getPath()));
            }
            else if(sysOssset.getState()>0&&ossFileExist(StringUtils.osspng(sysDocList.get(i).getPath())))
            {
                sysDocList.get(i).setPath("https://"+sysOssset.getBucket()+"."+sysOssset.getEndpoint()+"/"+StringUtils.osspng(sysDocList.get(i).getPath()));
            }
            else
            {
                sysDocList.get(i).setPath("/img/doc.png");
            }
        }
        modelMap.put("pagesize",10);
        modelMap.put("cpage", TableSupport.buildPageRequest().getPageNum());
        modelMap.put("total",sysDocList.size());
        modelMap.put("docs",sysDocList);
        //*****
        modelMap.put("type",typeNames);
        modelMap.put("one",one);
        modelMap.put("two",two);
        modelMap.put("three",three);
        modelMap.put("filterstr",second);
        modelMap.put("filter_array",filterhlist);
        modelMap.put("child_array", typeList);
        modelMap.put("parent_array",parent_array);
        modelMap.put("first",first);
        modelMap.put("third",third);
        modelMap.put("navurl",getRequest().getRequestURI());
        getabout(modelMap);
        return "doc/list";
    }
    //收藏
    @GetMapping ({"/doc/report.html"})
    public String report(HttpServletRequest request,ModelMap modelMap,@RequestParam("docid") long docid)  {
        long userid = -1;
        if(ShiroUtils.getSubject().getPrincipal() == null) {
            if (!(StringUtils.getCookie(request, "userid")).isEmpty())
                userid = Long.parseLong(StringUtils.getCookie(request, "userid"));
        }
        else
        {
            userid = ShiroUtils.getSysMember().getUserid();
        }
        SysReportItem sysReportItem = new SysReportItem();
        sysReportItem.setState(1);
        List<SysReportItem> sysReportItemList = iSysReportItemService.selectSysReportItemList(sysReportItem);
        SysReport sysReport = new SysReport();
        sysReport.setDocid(docid);
        sysReport.setUserid(userid);
        List<SysReport> sysReportList = iSysReportService.selectSysReportList(sysReport);
        if(sysReportList.size()>0)
            sysReport = sysReportList.get(0);
        else
        {
            sysReport.setReportid(0l);
            sysReport.setReport(sysReportItemList.get(0).getTitle());

        }
        modelMap.put("report_item",sysReportItemList);
        modelMap.put("report",sysReport);
        modelMap.put("docid",docid);
        return "topic/report";

    }
    //在这里写这个函数感觉不是很合理
    public HashMap<Long, String> findParentIdsById(Long id, List<SysType> categories) {
        SysType category = categories.stream()
                .filter(c -> c.getTypeid().equals(id))
                .findFirst()
                .orElse(null);

        if (category != null) {
            parentIds.put(category.getTypeid(),category.getTypename());
            Long parentId = category.getPtypeid();
            if (parentId != null) {
                findParentIdsById(parentId, categories);
            }
        }

        return parentIds;
    }
    //获取所有id,包括自己
    public List<Long> getAllChildIds(List<SysType> categories, Long parentId) {
        List<Long> childIds = new ArrayList<>();
        for (SysType category : categories) {
            if (category.getPtypeid() == parentId) {
                childIds.add(category.getTypeid());
                List<Long> grandchildIds = getAllChildIds(categories, category.getTypeid());
                childIds.addAll(grandchildIds);
            }
        }
        return childIds;
    }
    //获取文档页数
    @GetMapping(value = {"/page.htm"}, produces = "image/svg+xml")
    public ResponseEntity<String> docpage(HttpServletResponse response, ModelMap model, @RequestParam("docid") long docid, @RequestParam(value = "page",defaultValue ="0") int pcurrent) throws IOException {
        SysDoc  sysDoc = iSysDocService.selectSysDocByDocid(docid);
        //获取.view 数目
        int hcount = CovertUtil.countFilesWithExtension(new File(StringUtils.getdir(sysDoc.getPath())),".view");
        //获取oss 存储的文件数目
        SysOssset sysOssset;
        sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
        String docpath = iSysDocService.selectSysDocByDocid(docid).getPath();
        String pre = Constants.RESOURCE_PREFIX;
        String dirname = RuoYiConfig.getProfile();
        String path = docpath.replace(pre,"");
        String aliyun_src = path.substring(0,path.indexOf(".")) + "/";
        aliyun_src = aliyun_src.substring(1);
        if(sysOssset.getState()>0)
        {

            OSS ossClient = new OSSClientBuilder().build(sysOssset.getEndpoint(), sysOssset.getKeyid(), sysOssset.getKeysecret());
            ObjectListing objectListing = ossClient.listObjects(new ListObjectsRequest(sysOssset.getBucket()).withMaxKeys(1000).withPrefix(aliyun_src));
            List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
            int fileCount = sums.size()-1;
            hcount = fileCount + hcount;
            ossClient.shutdown();
        }

        //结束
        int pcount = hcount;
        if (hcount == 0) {
            hcount = 1;
        }
        BigDecimal zero = BigDecimal.ZERO;
        BigDecimal bigDecimalValue = new BigDecimal(String.valueOf(sysDoc.getReadpay()));
        if (bigDecimalValue.compareTo(zero) == 0) {
            sysDoc.setPreview((long)hcount);
        } else {
            sysDoc.setPreview(sysDoc.getPreview() > hcount ? hcount : sysDoc.getPreview());
        }
        List<Long> typeids = Arrays.asList(-30L,-31L,-32L);
        //Long userid =   Long.valueOf(StringUtils.getCookie(getRequest(),"userid"));
        long userid = -1;
        if(ShiroUtils.getSubject().getPrincipal() == null) {
            if (!(StringUtils.getCookie(ServletUtils.getRequest(), "userid")).isEmpty())
                userid = Long.parseLong(StringUtils.getCookie(ServletUtils.getRequest(), "userid"));
        }
        else
        {
            userid = ShiroUtils.getSysMember().getUserid().intValue();
        }
        SysGlodpot sysGlodpotread = iSysGlodpotService.findTypeUseridLinked(typeids,userid,docid);
        if(sysGlodpotread!=null)
            sysDoc.setPreview((long)hcount);

        if(sysDoc.getUserid() == userid)
            sysDoc.setPreview((long)hcount);
        String content ="";
        if(pcurrent<=sysDoc.getPreview())
        {
           String svg = StringUtils.getdir(sysDoc.getPath()) + pcurrent +".view";
           if(new File(svg).exists())
           {
               //response.setContentType("image/svg+xml");
               try {
                   content = new String(Files.readAllBytes(Paths.get(svg)));
                   //System.out.println(content);
               } catch (IOException e) {
                   e.printStackTrace();
               }
               //response.getWriter().write(content);
           }
           //处理oss 获取文件逻辑
            else if(sysOssset.getState()>0&&ossFileExist(aliyun_src+ pcurrent +".view"))
           {
               OSS ossClient = new OSSClientBuilder().build(sysOssset.getEndpoint(), sysOssset.getKeyid(), sysOssset.getKeysecret());
               OSSObject ossObject = ossClient.getObject(sysOssset.getBucket(), aliyun_src+ pcurrent +".view");
               BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
               StringBuilder sb = new StringBuilder();
               try {
                   while (true) {
                       String line = reader.readLine();
                       if (line == null) {
                           break;
                       }
                       sb.append(line).append("\n");
                   }
                   reader.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
                content = sb.toString();
               // 关闭OSSClient。
               ossClient.shutdown();

           }
            else
           {
               try {
                   // 读取文件内容为String
                   content = new String(Files.readAllBytes(Paths.get("static/img/4.svg")));
                   System.out.println(content);
               } catch (IOException e) {
                   e.printStackTrace();
               }

           }
            //结束

        }
        SysWater sysWater = iSysWaterService.selectSysWaterList(new SysWater()).get(0);
        if(sysWater.getState()>0) //加水印
        {
             content = content.replace("</svg>", sysWater.getWatermark() + "</svg>");
        }

        return ResponseEntity.status(HttpStatus.OK)
                .header("Content-Type", "image/svg+xml;charset=UTF-8")
                .body(content);
    }
    //获取文档页数
    @GetMapping(value = {"/readpay.htm"})
    public String readpay( ModelMap model, @RequestParam("docid") long docid, @RequestParam("readpay") BigDecimal readpay,@RequestParam("readpay2") BigDecimal readpay2,@RequestParam("type") String type,@RequestParam("readdown") String readdown) {
        SysMember sysMember = ShiroUtils.getSysMember();
        if(sysMember == null)
            sysMember = new SysMember();
        List<SysTradeset> sysTradesets = iSysTradesetService.selectSysTradesetList(new SysTradeset());
        //SysDoc  sysDoc = iSysDocService.selectSysDocByDocid(docid);
        //model.put("sysdoc",sysDoc);
        model.put("id",docid);
        model.put("systradesets",sysTradesets.get(0));
        model.put("user",sysMember);
        model.put("type",type);
        model.put("pay",readpay);
        model.put("pay2",readpay2);
        model.put("readdown",readdown);
        List<SysLoginset> sysLoginsetList = iSysLoginsetService.selectSysLoginsetList(new SysLoginset());
        model.put("loginsetlist",sysLoginsetList);
        List<SysWeixinset> sysWeixinsetList = iSysWeixinsetService.selectSysWeixinsetList(new SysWeixinset());
        model.put("paysetlist",sysWeixinsetList);
         return "doc/pay";
    }
    //下载文档
    @GetMapping(value = {"/downdoc.htm"})
    public ResponseEntity<ByteArrayResource> downdoc(@RequestParam("docid") long docid) throws IOException {
        SysDoc doc = iSysDocService.selectSysDocByDocid(docid);
        long userid = -1;
        SysMember  sysMember = new SysMember();
        sysMember.setUserid(-1l);
        sysMember.setNickname("游客");
        sysMember.setGroupid(0l);
        if(ShiroUtils.getSubject().getPrincipal() == null) {
            if (!(StringUtils.getCookie(getRequest(), "userid")).isEmpty())
                userid = Long.parseLong(StringUtils.getCookie(getRequest(), "userid"));
                sysMember.setUserid(userid);

        }
        else
        {
            userid = ShiroUtils.getSysMember().getUserid().intValue();
            sysMember = ShiroUtils.getSysMember();
        }

        //新增下载次数
        iSysDocService.increaseDowncount(docid);
        //新增下载记录
        SysDownlog sysDownlog = new SysDownlog();
        sysDownlog.setUserid(sysMember.getUserid());
        sysDownlog.setDocid(docid);
        List<SysDownlog> sysDownlogList;
        sysDownlogList = iSysDownlogService.selectSysDownlogList(sysDownlog);
        if (sysDownlogList.size()>0)
        {
            iSysDownlogService.increaseDowncount(sysDownlogList.get(0).getLogid());

        }
        else
        {
            sysDownlog.setTitle(doc.getTitle());
            sysDownlog.setExten(doc.getExten());
            sysDownlog.setNickname(sysMember.getNickname());
            iSysDownlogService.insertSysDownlog(sysDownlog);

        }
        //结束

        String docpath = doc.getPath();
        String pre = Constants.RESOURCE_PREFIX;
        String dirname = RuoYiConfig.getProfile();
        String srcurl = dirname + docpath.replace(pre,"");
        String aliyun_src = docpath.replace(pre+"/","");
        String soucename = doc.getTitle() + "." + doc.getExten();
        byte[] bytes = new byte[0];
        //本地的文件
        SysOssset sysOssset;
        sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
        OSS ossClient = new OSSClientBuilder().build(sysOssset.getEndpoint(), sysOssset.getKeyid(), sysOssset.getKeysecret());
        if(new File(srcurl).exists()) {
            bytes = Files.readAllBytes(new File(srcurl).toPath());
        }
        else if(sysOssset.getState()>0&&ossFileExist(aliyun_src)) {
            OSSObject ossObject = ossClient.getObject(sysOssset.getBucket(),aliyun_src);
            InputStream inputStream = ossObject.getObjectContent();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] readBuffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(readBuffer)) != -1) {
                byteArrayOutputStream.write(readBuffer, 0, bytesRead);
            }
            // 获取最终的字节数组。
            bytes = byteArrayOutputStream.toByteArray();
        }

        ByteArrayResource bar = new ByteArrayResource(bytes);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header("Content-disposition", "attachment; filename=\"" + URLEncoder.encode(soucename) + "\";charset=utf-8")
                .body(bar);

    }

    @PostMapping ({"/upload/save"})
    @ResponseBody
    public boolean save(ParamDoc paramDoc) throws Exception {
        SysOssset sysOssset = new SysOssset();
        sysOssset = sysOsssetService.selectSysOsssetList(new SysOssset()).get(0);
        String accessKey = sysOssset.getKeyid();
        String bucketName = sysOssset.getBucket();
        String secretKey = sysOssset.getKeysecret();
        String region = sysOssset.getEndpoint();
        Long defile = sysOssset.getDelfile();
        SysDoc sysDoc = new SysDoc();
        sysDoc.setDocid(paramDoc.getDocid());
        sysDoc.setUserid(ShiroUtils.getSysMember().getUserid());
        sysDoc.setTitle(paramDoc.getTitle());
        sysDoc.setKeyword(paramDoc.getKeyword());
        sysDoc.setWord(paramDoc.getWord());
        sysDoc.setFilter(StringUtils.arrayTostr(paramDoc.getFilter(),"."));
        sysDoc.setTypeid(StringUtils.lastArray(paramDoc.getTypeid()));
        sysDoc.setReadpay(paramDoc.getReadpay());
        sysDoc.setPreview(paramDoc.getPreview());
        sysDoc.setDownpay(paramDoc.getDownpay());
        if(iSysDocService.updateSysDoc(sysDoc)>0) {
            String docpath = iSysDocService.selectSysDocByDocid(paramDoc.getDocid()).getPath();
            String pre = Constants.RESOURCE_PREFIX;
            String dirname = RuoYiConfig.getProfile();
            String path = docpath.replace(pre,"");
            String aliyun_src = path.substring(0,path.indexOf(".")) + "/";
            aliyun_src = aliyun_src.substring(1);
            String srcurl = dirname + docpath.replace(pre,"");
            File file = new File(srcurl);
            String filename = file.getName().substring(0,file.getName().indexOf("."));
            String srcpath  = srcurl.substring(0,srcurl.indexOf(".")) + "/";
            String strpath  = srcpath + filename +".pdf";
            String extName = file.getName().substring(file.getName().lastIndexOf(".") + 1);
            if(extName.equals("docx") || extName.equals("doc") || extName.equals("wps") || extName.equals("rtf") || extName.equals("ofd")) {
                CovertUtil.fileToPdf(srcurl,strpath,"0",srcpath,10);
                if(sysOssset.getState()>0)
                    uploadImg(path,srcurl,srcpath,aliyun_src,accessKey,secretKey,bucketName,region,defile);

            } else if(extName.equals("epub"))
            {
                CovertUtil.EpubToPdf(srcurl,strpath,"0",srcpath);
                if(sysOssset.getState()>0)
                    uploadImg(path,srcurl,srcpath,aliyun_src,accessKey,secretKey,bucketName,region,defile);

            }
            else if(extName.equals("ppt") || extName.equals("pptx") || extName.equals("dps") || extName.equals("pps") || extName.equals("pot")) {
                CovertUtil.fileToPdf(srcurl,strpath,"1",srcpath,10);
                if(sysOssset.getState()>0)
                    uploadImg(path,srcurl,srcpath,aliyun_src,accessKey,secretKey,bucketName,region,defile);

            }else if(extName.equals("txt"))
            {
                CovertUtil.txtToPdf(srcurl,strpath,"0",srcpath);
                if(sysOssset.getState()>0)
                    uploadImg(path,srcurl,srcpath,aliyun_src,accessKey,secretKey,bucketName,region,defile);

            }  else if(extName.equals("pdf"))
            {
                CovertUtil.downPdf(srcurl,strpath,"0",srcpath);
                if(sysOssset.getState()>0)
                    uploadImg(path,srcurl,srcpath,aliyun_src,accessKey,secretKey,bucketName,region,defile);

            }
            else if(extName.equals("csv"))
            {
                CovertUtil.fileToPdf(srcurl,strpath,"3",srcpath,10);
                if(sysOssset.getState()>0)
                    uploadImg(path,srcurl,srcpath,aliyun_src,accessKey,secretKey,bucketName,region,defile);

            }
            else
            {
                CovertUtil.fileToPdf(srcurl,strpath,"2",srcpath,10);
                if(sysOssset.getState()>0)
                    uploadImg(path,srcurl,srcpath,aliyun_src,accessKey,secretKey,bucketName,region,defile);

            }

            if(!extName.equals("pdf"))
            {

                if (new File(strpath).exists()) {
                    new File(strpath).delete();
                }
            }

           return true;
        }
        else
            return false;
    }
    public static void uploadImg(String path,String srcurl,String despath,String strpath,String accesskey,String secretkey,String bucketname,String region,Long delfile) {
        int imgcount = CovertUtil.countFilesWithExtension(new File(despath),".png");
        int viewcount = CovertUtil.countFilesWithExtension(new File(despath),".view");
        path = path.substring(1);
        CloudVo cloudVo = new CloudVo();
        cloudVo.setAccessKey(accesskey);
        cloudVo.setSecretKey(secretkey);
        //cloudVo.setDomain("http://oss.sishoe.com");
        cloudVo.setBucketName(bucketname);
        cloudVo.setRegion(region);
        //上传源文件(比如doc,excel等等)
        upload(cloudVo,path,srcurl,new File(srcurl));
        //上传完是否删除
        /*if(delfile==1)
        {
            File file = new File(srcurl);
            if (file.exists()) {
                file.delete();
            }

        }*/
        //上传图片
        for(int i=1;i<=imgcount;i++)
        {
            //上传文件
            upload(cloudVo,strpath+(i)+".png",despath+(i)+".png",new File(despath+(i)+".png"));
            //上传完是否删除
            /*if(delfile==1)
            {
                File file = new File(despath+(i)+".png");
                if (file.exists()) {
                    file.delete();
                }

            }*/


        }
        //上传view文件
        for(int i=1;i<=viewcount;i++)
        {

            upload(cloudVo,strpath+(i)+".view",despath+(i)+".view",new File(despath+(i)+".view"));
            /*if(delfile==1)
            {
                File file = new File(despath+(i)+".view");
                if (file.exists()) {
                    file.delete();
                }

            }*/
            if(delfile==1) {
                FileUtils.deleteFile(srcurl); //删除源文件
                FileUtils.deleteFolder(new File(strpath));
            }

        }

    }

    public static void upload(CloudVo cloudVo, String webPth, String localFile, File file) {
        //logger.info("上传文件开始：" + localFile);
        OSS ossClient = new OSSClientBuilder().build(cloudVo.getRegion(), cloudVo.getAccessKey(), cloudVo.getSecretKey());
        try {
            //判断bucket是否存在
            if (!ossClient.doesBucketExist(cloudVo.getBucketName())){
                ossClient.createBucket(cloudVo.getBucketName());
            }

            if(!file.exists()){
                //logger.info("上传文件" + localFile + "不存在：");
                return;
            }
            PutObjectRequest putObjectRequest = new PutObjectRequest(cloudVo.getBucketName(), webPth, file);
            // 上传文件。
            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            //logger.info("上传文件 -- 结束：" + putObjectResult.getETag());

        } catch (Exception e){

        } finally {
            ossClient.shutdown();
        }
    }


}